<?php

namespace App\Service\ExternalAPI;

use EchoPHP\Facades\Log;
use Exception;
use GuzzleHttp\Client;

/**
 * ES引擎接口
 * Class CaseResumeApi
 * @package App\Service\ExternalAPI
 */
class CaseResumeApi {

    private $_source = 'rpopro';

    /**
     * 接口地址
     * @var
     */
    protected $host;
    /**
     * 访问密码
     * @var
     */
    protected $accessPassword;
    /**
     * 接口版本
     * @var
     */
    protected $version;
    /**
     * 接口超时时间
     * @var
     */
    protected $timeout;

    protected $errorMsg;

    /**
     * 初始化接口
     * VApi constructor.
     * @throws Exception
     */
    public function __construct() {
        $options = config('extraapi.caseresume', []);
        $this->host = $options['host'];
        $this->version = $options['version'];
        $this->accessPassword = $options['access_password'];
        $this->timeout = $options['timeout'];
    }

    /**
     * Notes:根据CaseResume keycode
     * @param $params
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getResumeKeycodes($params) {
        $postData = $this->getPostData($params);
        $content = $this->searchResume($postData);
        return $content;
    }

    /**
     * 检查简历ID是否在ES引擎中
     * @param $resumeIds 1;2;3;
     * @param $params
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function checkResumeInEs($resumeIds) {
        $result = ['status' => false, 'message' => '', 'data' => ''];

        if (empty($resumeIds)) {
            $result['message'] = '参数不可为空';
            return $result;
        }
        $postData = ['resumeid' => $resumeIds];
        $result = $this->checkResumeByResumeIds($postData);
        return $result;
    }


    /**
     * 获取CaseResumeList数据
     * @param $resumeIds
     * @param $params
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getCaseResumeInfoByEs($params, $rowFrom = 0, $rowTo = 1000) {
        if ($rowFrom < 0) {
            $rowTo = 0;
        }
        if ($rowTo < 1) {
            $rowTo = 100;
        }
        if ($rowFrom > $rowTo) {
            $rowTo = $rowFrom;
        }

        $postData = [];
        $postData['resumeid'] = isset($params['resumeid']) ? $params['resumeid'] : '';
        $postData['tagadderid'] = isset($params['tagadderid']) ? $params['tagadderid'] : '';
        $postData['waitflow'] = isset($params['waitflow']) ? $params['waitflow'] : '';
        $postData['timecontrol_begin'] = isset($params['timecontrol_begin']) ? $params['timecontrol_begin'] : '';
        $postData['timecontrol_end'] = isset($params['timecontrol_end']) ? $params['timecontrol_end'] : '';

        $postData['subid'] = isset($params['subid']) ? $params['subid'] : '';
        $postData['projectid'] = isset($params['projectid']) ? $params['projectid'] : '';
        $postData['caseid'] = isset($params['caseid']) ? $params['caseid'] : '';

        $postData['updatedate_begin'] = isset($params['updatedate_begin']) ? $params['updatedate_begin'] : '';
        $postData['updatedate_end'] = isset($params['updatedate_end']) ? $params['updatedate_end'] : '';

        $postData['row_from'] = $rowFrom;
        $postData['row_to'] = $rowTo;

        $postData['access_password'] = $this->accessPassword;
        $postData['version'] = $this->version;

        $content = $this->getCaseResumeInfo($postData);
        return $content;
    }


    /**
     * 获取待跟进数据（按日期查询总数）
     * @param $resumeIds
     * @param $params
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getWaitFlowTotalNum($oprId, $search_type, $waitflow, $timecontrol_begin, $timecontrol_end, $rowFrom = 0, $rowTo = 100) {
        if ($rowFrom < 0) {
            $rowTo = 0;
        }
        if ($rowTo < 1) {
            $rowTo = 100;
        }
        if ($rowFrom > $rowTo) {
            $rowTo = $rowFrom;
        }

        $postData = [];
        $postData['tagadderid'] = $oprId;
        $postData['waitflow'] = $waitflow;
        $postData['search_type'] = $search_type;
        $postData['timecontrol_begin'] = $timecontrol_begin;
        $postData['timecontrol_end'] = $timecontrol_end;
        $postData['row_from'] = $rowFrom;
        $postData['row_to'] = $rowTo;

        $postData['access_password'] = $this->accessPassword;
        $postData['version'] = $this->version;

        $content = $this->getTotalNumInfo($postData);
        return $content;
    }


    /**根据简历ID返回简历是否在ES引擎中
     * @param $postData
     * @return |null
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function checkResumeByResumeIds($postData) {
        $requestUrl = '/search_exist_resumeid';

        $client = new Client([
            'base_uri' => $this->host,
            'timeout' => $this->timeout
        ]);

        $postData['access_password'] = $this->accessPassword;
        $postData['version'] = $this->version;

        try {
            $response = $client->request('POST', $requestUrl, [
                'json' => $postData
            ]);
            $content = $response->getBody()->getContents();
            $content = json_decode($content, true);

            if (!isset($content['result'])) {
                throw new Exception('ES简历查询接口未返回result字段');
            }
            if ($content['result'] != 0) {
                throw new Exception('ES简历查询接口调用失败,result[' . $content['result'] . '];errinfo[' . $content['errinfo'] . ']');
            }
            return [
                'status' => true,
                'message' => '',
                'data' => $content['data']
            ];
        } catch (Exception $e) {
            Log::error($e->getMessage(), [
                'requestUrl' => $requestUrl,
                'postData' => $postData,
            ]);
            return [
                'status' => false,
                'message' => 'ES引擎失败',
                'data' => ''
            ];
        }
    }


    /**获取企业库简历接口
     * @param $postData
     * @return |null
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function searchResume($postData) {
        $requestUrl = '/search_resumeid_projectid';

        $client = new Client([
            'base_uri' => $this->host,
            'timeout' => $this->timeout
        ]);

        try {
            $response = $client->request('POST', $requestUrl, [
                'json' => $postData
            ]);
            $content = $response->getBody()->getContents();
            $content = json_decode($content, true);
            if (!isset($content['result'])) {
                throw new Exception('ES简历查询接口未返回result字段');
            }
            if ($content['result'] != 0) {
                throw new Exception('ES简历查询接口调用失败,result[' . $content['result'] . '];errinfo[' . $content['errinfo'] . ']');
            }
            //debug模式下，记录接口调用日志
            if (env('APP_DEBUG')) {
                Log::info('ES简历查询接口数据', [
                    'requestUrl' => $requestUrl,
                    'postData' => $postData,
                ]);
            }
            return [
                'data' => $content['data'],
                'totalnum' => $content['totalnum']
            ];
        } catch (Exception $e) {
            Log::error($e->getMessage(), [
                'requestUrl' => $requestUrl,
                'postData' => $postData,
            ]);

            return [
                'data' => '',
                'totalnum' => 0,
                'eserror' => 1
            ];
        }
    }

    /**根据指定的时间范围，统计操作人待跟进的数据，全部或以天为单位统计
     * @param $postData
     * @return |null
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function getTotalNumInfo($postData) {
        $requestUrl = '/search_waitflow_totalnum';

        $client = new Client([
            'base_uri' => $this->host,
            'timeout' => $this->timeout
        ]);

        //var_dump($requestUrl);
        //var_dump(['json' => $postData]);
        try {
            $response = $client->request('POST', $requestUrl, [
                'json' => $postData
            ]);
            $content = $response->getBody()->getContents();
            if (empty($content)) {
                throw new Exception('接口未返回内容');
            }

            $content = json_decode($content, true);

            if (!isset($content['result'])) {
                throw new Exception('接口未返回result字段');
            }

            if ($content['result'] != 0) {
                throw new Exception('接口返回结果失败');
            }

            if (!isset($content['number_detail'])) {
                throw new Exception('接口未返回number_detail字段');
            }

            $total = $content['total_number'];

            $detailList = [];
            //以天为单位统计
            if ($postData['search_type'] == 2) {
                $content_rows = explode(';', $content['number_detail']);
                if (count($content_rows) < 1) {
                    throw new Exception('接口返回内容为空');
                }

                $total = 0;
                foreach ($content_rows as $key => $item) {
                    $item_rows = explode('_', $item);
                    if (count($item_rows) < 2) {
                        continue;
                    }

                    $detailList[] = [
                        'date' => $item_rows[0],
                        'day' => date('j', strtotime($item_rows[0])),
                        'num' => $item_rows[1]
                    ];
                    $total += $item_rows[1];
                }
            }

            $dateKey = array_column($detailList, 'date');
            array_multisort($dateKey, SORT_ASC, $detailList);

            $resultList = ['total' => $total, 'detail' => $detailList];
            return $resultList;
        } catch (Exception $e) {
            Log::error($e->getMessage(), [
                'requestUrl' => $requestUrl,
                'postData' => $postData,
            ]);
            return ['total' => 0, 'detail' => []];
        }
    }

    /**获取caseresume明细数据
     * @param $postData
     * @return |null
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function getCaseResumeInfo($postData) {
        $requestUrl = '/resumeid_data';

        $client = new Client([
            'base_uri' => $this->host,
            'timeout' => $this->timeout
        ]);

        //var_dump($requestUrl);
        //var_dump(['json' => $postData]);
        try {
            $response = $client->request('POST', $requestUrl, [
                'json' => $postData
            ]);
            $content = $response->getBody()->getContents();

            if (empty($content)) {
                throw new Exception('接口未返回内容');
            }
            $content = json_decode($content, true);

            if (!isset($content['result'])) {
                throw new Exception('接口未返回result字段');
            }

            if ($content['result'] != 0) {
                throw new Exception('接口返回结果失败');
            }

            if (!isset($content['data'])) {
                throw new Exception('接口未返回data字段');
            }

            if (empty($content['data'])) {
                return [];
                //throw new Exception('数据内容为空');
            }

            $content_rows = explode(chr(26), $content['data']);
            if (count($content_rows) < 1) {
                throw new Exception('接口返回内容为空');
            }

            $itemNameStr = 'keycode,caseresumeid,resumeid,projectid,caseid,subid,flowat,';
            $itemNameStr .= 'flowatstatus,tagadderid,tagadddate,timecontrol,waitflow';
            $itemNameArr = explode(',', $itemNameStr);

            $caseResumeList = [];
            foreach ($content_rows as $key => $item) {
                $item_rows = explode(chr(16), $item);
                if (count($item_rows) < 4) {
                    throw new Exception('接口返回内容解析异常');
                    break;
                }
                $item_obj = [];
                foreach ($item_rows as $key => $item) {
                    if (in_array($itemNameArr[$key], ['tagadddate', 'timecontrol'])) {
                        $item = date('Y-m-d H:i:s', $item);

                    }
                    $item_obj[$itemNameArr[$key]] = $item;
                }
                $caseResumeList[] = $item_obj;
            }

            /*
            if(isset($postData['timecontrol_begin']) && $postData['timecontrol_begin']!='') {
                $timecontrolKey = array_column($caseResumeList, 'timecontrol');
                $caseresumeidKey = array_column($caseResumeList, 'caseresumeid');
                array_multisort($timecontrolKey, SORT_ASC, $caseresumeidKey, SORT_DESC, $caseResumeList);
            }*/

            return $caseResumeList;
        } catch (Exception $e) {
            Log::error($e->getMessage(), [
                'requestUrl' => $requestUrl,
                'postData' => $postData,
            ]);
            return [];
        }
    }

    /**
     * Notes:推送简历标签变动
     * @param $params
     * @return array|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function syncCaseFlow($params) {
        $requestUrl = '/operation_case_caseflow';

        $client = new Client([
            'base_uri' => $this->host,
            'timeout' => $this->timeout
        ]);
        $params['access_password'] = $this->accessPassword;
        $params['version'] = $this->version;
        $content = [];
        try {
            $response = $client->request('POST', $requestUrl, [
                'json' => $params
            ]);
            $content = $response->getBody()->getContents();
//            Log::debug('流程变动推送', [
//                'centent' => $content,
//                'postData' => $params,
//            ]);
            if (empty($content)) {
                throw new Exception('接口未返回内容');
            }
            $content = json_decode($content, true);
            if ($content['result'] != 0) {
                throw new Exception('ES流程推送失败');
            }
            return true;
        } catch (Exception $e) {
            Log::error($e->getMessage(), [
                'requestUrl' => $requestUrl,
                'postData' => $params,
                'result' => $content,
            ]);
            return ['total' => 0, 'detail' => []];
        }
    }


    /**
     * Notes:获取请求参数，未用到的参数暂时不需要传
     * @param $params
     * @return array
     */
    private function getPostData($params) {
        return [
            "projectid" => $params['projectid'],
            "caseid" => $params['caseid'] ?? '',
            'flowat_flowatstatus' => $params['flowat'] ?? '',
            'tagadderid' => $params['tagadderid'] ?? '',
            'caseresume_type' => $params['caseresume_type'],
            'cname' => $params['cname'] ?? '',
            'mobilephone' => $params['mobilephone'] ?? '',
            'email' => $params['email'] ?? '',
            'tagadddate_begin' => $params['tagadddate_begin'] ?? '',
            'tagadddate_end' => $params['tagadddate_end'] ?? '',
            'creator' => $params['creator'] ?? '',
//            "gender" => '',
//            "degree" => '',
//            "major" => '',
//            "funtype" => '',
//            "workindustry" => '',
//            "expectarea" => '',
//            "area" => '',
//            "start_workyear" => '',
//            "end_workyear" => '',
//            "birthday" => '',
//            "position" => '',
//            "company" => '',
//            "expsalaryfrom" => '',
//            "expsalaryto" => '',
//            "currsalaryfrom" => '',
//            "currsalaryto" => '',
            "access_password" => $this->accessPassword,
            "version" => $this->version
        ];
    }
}